<?php

namespace app\store\model;

use app\common\model\dealer\Referee as RefereeModel;
use app\common\model\User as UserModel;
use app\common\model\user\PointsLog as PointsLogModel;

/**
 * 用户模型
 * Class User
 * @package app\store\model
 */
class User extends UserModel
{
    /**
     * 获取当前用户总数
     * @param $day
     * @return int|string
     */
    public function getUserTotal($day = null)
    {
        if (!is_null($day)) {
            $startTime = strtotime($day);
            $this->where('create_time', '>=', $startTime)
                ->where('create_time', '<', $startTime + 86400);
        }
        return $this->count();
    }

    /**
     * 获取用户列表
     * @param string $search 昵称或手机号
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($search = '', $gender = -1, $grade = null)
    {
        // 检索：微信昵称或手机号
        !empty($search) && $this->where('nickName|mobile|device_sn|real_name', 'like', '%' . trim($search) . '%');
        // 检索：性别
        if ($gender !== '' && $gender > -1) {
            $this->where('gender', '=', (int)$gender);
        }
        // 检索：会员等级
        $grade > 0 && $this->where('grade_id', '=', (int)$grade);
        // 获取用户列表
        $data =  $this->with(['grade'])
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate(15, false, [
                'query' => \request()->request()
            ]);
        return $this->setRefereeUserList($data);
    }

    /**
     * 获取推荐人
     * @param $userList
     * @return mixed
     * @throws \think\exception\DbException
     */
    private function setRefereeUserList($userList)
    {
        foreach ($userList as $key => $value) {
            $userList[$key]['referee'] = RefereeModel::getRefereeUser($value['user_id'], 1);
        }
        return $userList;
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 用户充值
     * @param string $storeUserName 当前操作人用户名
     * @param array $data post数据
     * @return bool
     */
    public function recharge($storeUserName, $data)
    {
        if (!isset($data['value']) || $data['value'] === '' || $data['value'] < 0) {
            $this->error = '请输入正确的积分数量';
            return false;
        }
        // 判断充值方式，计算最终积分
        if ($data['mode'] === 'inc') {
            $diffMoney = $data['value'];
            $diffPoints = $data['value'];
        } elseif ($data['mode'] === 'dec') {
            $diffMoney = -$data['value'];
            $diffPoints = -$data['value'];
        } else {
            $diffMoney = $data['value'] - $this['points'];
            $diffPoints = $data['value'] - $this['total_points'];
        }
        // 更新记录
        $this->transaction(function () use ($storeUserName, $data, $diffMoney, $diffPoints) {
            // 更新账户积分
            $this->setInc('points', $diffMoney);
            $this->setInc('total_points', $diffPoints);
            // 新增积分变动记录
            PointsLogModel::add([
                'user_id' => $this['user_id'],
                'value' => $diffMoney,
                'scene' => $data['mode'] === 'inc' ? 20 : 10,
                'describe' => "后台管理员 [{$storeUserName}] 操作",
                'shop_type' => 20,
                'scene_type' => 30,
                'remark' => $data['remark'],
            ]);
        });
        return true;
    }

    /**
     * 更新记录
     * @param $data
     * @return bool|int
     */
    public function edit($data)
    {
        if (!isset($data['device_sn']) || empty($data['device_sn'])) {
            $this->error = '请填写SN码';
            return false;
        }
        return $this->allowField(true)->save($data) !== false;
    }


}
